package com.crayon2f.test.pdf;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.io.IOException;

public class PdfHeaderUtil {

    public static void addPerfectHeader(PDDocument document, String imagePath) throws IOException {
        PDImageXObject headerImage = PDImageXObject.createFromFile(imagePath, document);

        PDPageTree pages = document.getPages();
        int pageNumber = document.getNumberOfPages();
        for (int i = 0; i < pageNumber; i++) {
            if (i == 0 || i == pageNumber - 1) {
                continue;
            }
            PDPage page = pages.get(i);
            PDRectangle mediaBox = page.getMediaBox();
            float pageWidth = mediaBox.getWidth();
            float pageHeight = mediaBox.getHeight();

            try (PDPageContentStream contentStream = new PDPageContentStream(
                    document, page, PDPageContentStream.AppendMode.APPEND, true)) {

                // 页眉参数配置
                float maxHeaderHeight = 35f; // 最大高度35点
                float minHeaderHeight = 20f;  // 最小高度20点
                float sideMargin = 50f;       // 左右边距
                float minTopMargin = 28.35f;  // 1cm ≈ 28.35点（最小顶部距离）

                // 计算最佳尺寸并缩小50%
                float availableWidth = pageWidth - 2 * sideMargin;
                float widthScale = availableWidth / headerImage.getWidth();
                float heightScale = maxHeaderHeight / headerImage.getHeight();
                float scale = Math.min(widthScale, heightScale) * 0.5f; // 缩小50%

                // 确保不低于最小高度
                float finalHeight = headerImage.getHeight() * scale;
                if (finalHeight < minHeaderHeight) {
                    scale = minHeaderHeight / headerImage.getHeight();
                }

                float imageWidth = headerImage.getWidth() * scale;
                float imageHeight = headerImage.getHeight() * scale;

                // 计算位置（水平居中，并确保距离顶部至少1cm）
                float x = (pageWidth - imageWidth) / 2;
                float y = pageHeight - imageHeight - minTopMargin; // 下移1cm

                System.out.printf("页眉尺寸: %.1f×%.1f, 位置: (%.1f, %.1f)%n",
                        imageWidth, imageHeight, x, y);

                // 绘制页眉图片
                contentStream.drawImage(headerImage, x, y, imageWidth, imageHeight);
            }
        }
    }
}